package com.sfc.spiderweb;

import com.alibaba.fastjson.JSON;
import com.sfc.spiderweb.entity.po.spider.*;
import com.sfc.spiderweb.service.adb.AmazonDataCompareService;
import com.sfc.spiderweb.service.spider.*;
import com.sfc.spiderweb.util.AmountUtils;
import com.sfc.spiderweb.util.BeanUtil;
import com.sfc.spiderweb.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
@ActiveProfiles("devp")
public class AmazonBillData {

    private static List<String> monthList = Arrays.asList("202001", "202002", "202003", "202004", "202005", "202006");

    //按每3个一组分割
    private static final Integer MAX_NUMBER = 1000;

    @Autowired
    private AmazonBillDataAeService aeService;

    @Autowired
    private AmazonBillDataAuService auService;

    @Autowired
    private AmazonBillDataBrService brService;

    @Autowired
    private AmazonBillDataCaService caService;

    @Autowired
    private AmazonBillDataComService comService;

    @Autowired
    private AmazonBillDataJpService jpService;

    @Autowired
    private AmazonBillDataMxService mxService;

    @Autowired
    private AmazonBillDataNlSgService nlSgService;

    @Autowired
    private AmazonBillDataSaService saService;

    @Autowired
    private AmazonBillDataUkDeEsFrItService ukDeEsFrItService;

    @Autowired
    private AmazonBillDataInService inService;

    @Autowired
    private AmazonDataCompareService amazonDataCompareService;

    @Test
    public void saveAmazonBillData() throws Exception {
        for (String month : monthList) {
            String billDatePath = "D:\\财务\\账单\\amazon\\amazon" + month + "\\" + month;
            start(billDatePath, month);
        }
    }

    private void start(String billDatePath, String month) throws Exception {
        File file = new File(billDatePath);
        File[] files = file.listFiles();
        for (File file1 : files) {
            String account = file1.getName();
            String site = account.toUpperCase().replaceAll("[0-9]|SSP[0-9]*", "").substring(account.lastIndexOf(".") + 1);
            if (!site.equals("BR")) {
                continue;
            }
            File[] files1 = file1.listFiles();
            if (files1.length < 1) {
                continue;
            }
            List<AmazonBillDataConvert> amazonBillDataConverts = new ArrayList<>();
            for (File file2 : files1) {
                if (file2.getName().endsWith(".csv")) {
                    if (site.equals("BR") && !month.equals("202005") && file2.getName().contains("Deferred")) {
                        continue;
                    }
                    if (site.equals("BR") && month.equals("202006") && file2.getName().contains("Custom")) {
                        continue;
                    }
                    List<List<String>> csvList;
                    if (site.equalsIgnoreCase("JP")) {
                        csvList = FileUtil.readJpCsv(file2.getAbsolutePath());
                    } else {
                        csvList = FileUtil.readCsv(file2.getAbsolutePath());
                    }
                    csvList = csvList.stream().filter(list1 -> list1.size() > 13 && !StringUtils.isEmpty(list1.get(1))).collect(Collectors.toList());
                    if (CollectionUtils.isEmpty(csvList)) {
                        continue;
                    }
                    int csvSize = csvList.get(0).size();
                    if (site.equals("BR")) {
                        List<List<String>> newCsvList = new ArrayList<>();

                        for (List<String> list : csvList) {
                            if (csvSize == 20) {
                                list.add(8, "");
                                list.add(13, "");
                                list.add(15, "");
                                list.add(17, "");
                                list.add(19, "");
                            } else if (csvSize == 21) {
                                list.add(13, "");
                                list.add(15, "");
                                list.add(17, "");
                                list.add(19, "");
                            } else {
                                list.add(8, "");
                            }
                            newCsvList.add(list);
                        }
                        csvList = newCsvList;
                    }
                    if (site.equals("COM") && csvSize < 28) {
                        List<List<String>> newCsvList = new ArrayList<>();
                        for (List<String> list : csvList) {
                            list.add(8, "");
                            newCsvList.add(list);
                        }
                        csvList = newCsvList;
                    }
                    if (site.equals("MX") && csvSize < 25) {
                        List<List<String>> newCsvList = new ArrayList<>();
                        for (List<String> list : csvList) {
                            list.add(17, "");
                            list.add(18, "");
                            list.add(21, "");
                            newCsvList.add(list);
                        }
                        csvList = newCsvList;
                    }
                    csvList = csvList.subList(1, csvList.size());
                    List<String> columnList = amazonDataCompareService.getColumnList(site);
                    for (List<String> list : csvList) {

                        AmazonBillDataConvert amazonBillDataConvert;
                        Map<String, String> map = new HashMap<>();
                        for (int i = 0; i < list.size(); i++) {
                            String key = "column" + (i + 1);
                            if (columnList.contains(key)) {
                                map.put(key, AmountUtils.formatAmount(list.get(i)));
                            } else {
                                map.put(key, list.get(i));
                            }
                        }
                        amazonBillDataConvert = JSON.parseObject(JSON.toJSONString(map), AmazonBillDataConvert.class);
                        amazonBillDataConvert.setMonth(month);
                        amazonBillDataConvert.setPlatform("amazon");
                        amazonBillDataConvert.setAccount(account);
                        amazonBillDataConvert.setSite(site);
                        amazonBillDataConverts.add(amazonBillDataConvert);
                    }

                }
            }
            if (!CollectionUtils.isEmpty(amazonBillDataConverts)) {
                int limit = countStep(amazonBillDataConverts.size());
                //使用流遍历分割list
                List<List<AmazonBillDataConvert>> mglist = new ArrayList<>();
                Stream.iterate(0, n -> n + 1).limit(limit).forEach(i -> {
                    mglist.add(amazonBillDataConverts.stream().skip(i * MAX_NUMBER).limit(MAX_NUMBER).collect(Collectors.toList()));
                });
                for (List<AmazonBillDataConvert> billDataConverts : mglist) {
                    switch (site) {
                        case "AE":
                            List<AmazonBillDataAe> billDataAes = BeanUtil.copyList(billDataConverts, AmazonBillDataAe.class);
                            aeService.insertBatch(billDataAes);
                            break;
                        case "AU":
                            List<AmazonBillDataAu> billDataAus = BeanUtil.copyList(billDataConverts, AmazonBillDataAu.class);
                            auService.insertBatch(billDataAus);
                            break;
                        case "BR":
                            List<AmazonBillDataBr> billDataBrs = BeanUtil.copyList(billDataConverts, AmazonBillDataBr.class);
                            brService.insertBatch(billDataBrs);
                            break;
                        case "CA":
                            List<AmazonBillDataCa> billDataCas = BeanUtil.copyList(billDataConverts, AmazonBillDataCa.class);
                            caService.insertBatch(billDataCas);
                            break;
                        case "COM":
                            List<AmazonBillDataCom> billDataComs = BeanUtil.copyList(billDataConverts, AmazonBillDataCom.class);
                            comService.insertBatch(billDataComs);
                            break;
                        case "JP":
                            List<AmazonBillDataJp> billDataJps = BeanUtil.copyList(billDataConverts, AmazonBillDataJp.class);
                            jpService.insertBatch(billDataJps);
                            break;
                        case "MX":
                            List<AmazonBillDataMx> billDataMxes = BeanUtil.copyList(billDataConverts, AmazonBillDataMx.class);
                            mxService.insertBatch(billDataMxes);
                            break;
                        case "NL":
                        case "SG":
                            List<AmazonBillDataNlSg> billDataNlSgs = BeanUtil.copyList(billDataConverts, AmazonBillDataNlSg.class);
                            nlSgService.insertBatch(billDataNlSgs);
                            break;
                        case "SA":
                            List<AmazonBillDataSa> billDataSas = BeanUtil.copyList(billDataConverts, AmazonBillDataSa.class);
                            saService.insertBatch(billDataSas);
                            break;
                        case "UK":
                        case "DE":
                        case "ES":
                        case "FR":
                        case "IT":
                            List<AmazonBillDataUkDeEsFrIt> billDataUkDeEsFrIts = BeanUtil.copyList(billDataConverts, AmazonBillDataUkDeEsFrIt.class);
                            ukDeEsFrItService.insertBatch(billDataUkDeEsFrIts);
                            break;
                        case "IN":
                            List<AmazonBillDataIn> billDataIns = BeanUtil.copyList(billDataConverts, AmazonBillDataIn.class);
                            inService.insertBatch(billDataIns);
                            break;
                        default:
                            log.error("站点信息异常");
                    }
                }
            }
        }
    }

    /**
     * 计算切分次数
     */
    private static Integer countStep(Integer size) {
        return (size + MAX_NUMBER - 1) / MAX_NUMBER;
    }
}
